﻿using drinking.Helpers;
using drinking.Managers;
using drinking.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace drinking.Api.Equip
{
    [Route("api/equip/")]
    [ApiController]
    public class EquipController : ControllerBase
    {
        /// <summary>
        /// 设备登录
        /// </summary>
        /// <param name="storeCode"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost("login")]
        public ApiResult Login(string storeCode, string password)
        {
            Store store = new DBContext().Db.Queryable<Store>().First(s => s.StoreCode == storeCode && s.Password == password);
            //var table = 
            if (store == null)
            {
                // 登录失败
                return ApiResult.Fail("账号或密码错误");
            }
            else
            {
                // 登录成功返回一个id
                return ApiResult.Success();
            }
        }

        /// <summary>
        /// 设备心跳 + 获取订单
        /// </summary>
        /// <param name="storeStatus">0： 正常  10：设备不通（上位机和设备） 20：心跳不通（上位机和服务器）</param>
        /// <param name="heartbeatTime">心跳时间</param>
        /// <returns></returns>
        [HttpPost("getOrder")]
        public ApiResult GetOrder(int storeStatus, string heartbeatTime, string storeCode, string password)
        {
            // 根据门店编码和密码找出当前 门店对象 在 缓存列表中的索引
            int storeIndex = StoreManager.GetStoresIndex4Pwd(storeCode, password);

            // 如果门店对象不存在，返回-1
            if (storeIndex == -1)
            {
                return ApiResult.Fail(ResultCode.NO_LOGON, "认证错误");
            }
            var db = new DBContext().Db;
            if (storeStatus != StoreManager.CacheStores[storeIndex].StoreStatus)
            {
                // 更新缓存
                StoreManager.CacheStores[storeIndex].StoreStatus = storeStatus;
                // 数据库更新
                db.Updateable<Store>(StoreManager.CacheStores[storeIndex]).UpdateColumns(store => new { store.StoreStatus }).ExecuteCommand();
            }

            List<Order> orders = new List<Order>();
            // 设备在线
            if (storeStatus == 0)
            {
                // 更新心跳时间
                StoreManager.CacheStores[storeIndex].HeartbeatTime = DateTime.Parse(heartbeatTime);

                //查询出当前状态为已支付10的该门店 的订单
                orders = db.Queryable<Order>().Where(order => order.StoreId == StoreManager.CacheStores[storeIndex].StoreId && order.OrderStatus == 10)
                .ToList();

                // 给每个订单添加添加明细 （一个订单里面可能有多杯奶茶）
                foreach (var order in orders)
                {
                    order.OrderItems = db.Queryable<OrderItem>().Where(item => item.OrderId == order.OrderId).ToList();
                }
            }
            return ApiResult.Success(orders);
        }

        /// <summary>
        /// 设备反馈订单状态
        /// </summary>
        /// <param name="OrderId"></param>
        /// <param name="orderStatus"></param>
        /// <returns></returns>
        [HttpPost("order")]
        public ApiResult Order(int orderStatus, int orderId, string time, string storeCode, string password)
        {
            int storeIndex = StoreManager.GetStoresIndex4Pwd(storeCode, password);
            if (storeIndex == -1)
            {
                return ApiResult.Fail(ResultCode.NO_LOGON, "认证错误");
            }
            var db = new DBContext().Db;

            // 根据订单id查出订单数据
            Order order = db.Queryable<Order>().InSingle(orderId);

            if (order == null)
            {
                return ApiResult.Fail("订单号错误");
            }

            // 如果状态为制作完成50， 更新制作完成的时间
            if (orderStatus == 50)
            {
                order.CompleteTime = time;
            }

            db.Updateable<Order>(order).UpdateColumns(o => new { o.OrderStatus, o.CompleteTime });

            return ApiResult.Success();
        }
    }
}
